package com.hyzh.latte.sandtable.mapper;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.hyzh.latte.sandtable.pojo.GeoQuery.IndexAndPoint;
import com.hyzh.latte.sandtable.pojo.Vector_Line_2D;
import com.hyzh.latte.sandtable.pojo.Vector_Point_2D;
import org.apache.ibatis.annotations.*;

@Mapper
@DS("sadt")
public interface GeoQueryMapper {
    @Select("SELECT index, ST_AsText(ST_ClosestPoint(geom, ST_SetSRID(ST_Point(#{point.x}, #{point.y}), 4326))) as point0 " +
            "FROM ${area} " +
            "ORDER BY geom <-> ST_SetSRID(ST_Point(#{point.x}, #{point.y}), 4326) " +
            "LIMIT 1")
    IndexAndPoint findClosestLineToPoint(@Param("point") Vector_Point_2D point, @Param("area") String area);

    @Select("SELECT length " +
            "FROM ${area} " +
            "WHERE index = #{lineIndex}")
    double selectLengthByLineIndex(@Param("lineIndex")Integer lineIndex, @Param("area") String area);

    @Select("SELECT index FROM ${area} " +
            "WHERE ST_Equals(geom, ST_SetSRID(ST_MakePoint(#{point.x}, #{point.y}), 4326))")
    Integer selectNodeIndexByCoords(@Param("point") Vector_Point_2D point, @Param("area") String area);

    @Select("SELECT index, start_x, start_y, end_x, end_y, length " +
            "FROM ${area} " +
            "WHERE index = #{index}")
    Vector_Line_2D selectLineByIndex(@Param("index") Integer index, @Param("area") String area);

    @Select("SELECT ST_DistanceSphere(" +
            "ST_SetSRID(ST_MakePoint(#{point0.x}, #{point0.y}), 4326), " +
            "ST_SetSRID(ST_MakePoint(#{point1.x}, #{point1.y}), 4326))")
    double getDistanceBetweenTwoPoints(@Param("point0") Vector_Point_2D point0, @Param("point1") Vector_Point_2D point1);

    @Select("SELECT index FROM ${area} " +
            "WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint(#{point.x}, #{point.y}), 4326), 0) " +
            "ORDER BY ST_Distance(geom, ST_SetSRID(ST_MakePoint(#{point.x}, #{point.y}), 4326)) " +
            "LIMIT 1")
    Integer findClosestPoint(@Param("point") Vector_Point_2D point,@Param("area") String area);
}
